<?php

namespace App\Http\Controllers;

use App\Models\Car;
use App\Models\Merchant\GiftLog;
use App\Models\MyCar;
use App\Models\MyStage;
use App\Models\Stage;
use App\Repos\MemberRepo;
use App\Repos\MessageRepo;
use App\Services\GoldShopService;
use App\Transformers\CarTransformer;
use App\Transformers\StageTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StoreController extends ApiController
{
    protected $goldShopService;

    public function __construct(GoldShopService $gss)
    {
        parent::__construct();
        $this->goldShopService = $gss;
    }
    //获取可供销售的车辆
    public function cars(CarTransformer $carTransfomer)
    {
        $cars = Car::forSell()->paginate($this->request->input('paginate',20));
        $list = $carTransfomer->setTransformer('forSell')->listData($cars->getCollection());
        
        return $this->setPage($cars->hasMorePages())->success($list);
    }
    
    //获取可供销售的道具
    public function stages(StageTransformer $stageTransfomer)
    {
        $stages = Stage::forSell()->orderBy('StagePrice')->paginate($this->request->input('paginate',20));
        
        $list = $stages->transform(function($item){
            $item['hold'] = MyStage::where('StageID',$item->StageID)->where('uid',$this->user->id)->where('car_id',0)->count()?:0;
            return $item;
        });
        $list = $stageTransfomer->setTransformer('forSell')->listData($list);
        
        return $this->setPage($stages->hasMorePages())->success($list);
    }
    
    
    //买车
    public function buyCar(MemberRepo $memberRepo)
    {
        $car_id = $this->request->car_id;
        $car = Car::forSell()->findOrFail($car_id);
    
        //检查是否已拥有此车- 弃用
        //if(MyCar::where('uid',$this->user->id)->where('CarID',$car_id)->exists()){
        //    return $this->error(1,'用户已拥有此车');
        //}
    
        $car_buyed = MyCar::where('uid',$this->user->id)->count();
        $max_cars_limit = \count(config('car.levels'));
        //检查总购买限制
        if($car_buyed >= $max_cars_limit){
            return $this->error(1,'您最多只能购买'.$max_cars_limit.'辆车');
        }
        //检查用户拥有车的上限
        if($car_buyed >= $this->user->getCarLimit()){
            return $this->error(1,'非常抱歉，您需要升级车库才能购买第'.($this->user->getCarLimit()+1).'辆车');
        }
        
        
        //如果用户有可兑换此车的奖品
        //$gift_log = GiftLog::sended()->unused()
        //    ->where('user_id',$this->user->id)->where('category',3)->where('extra',$car_id)->first();
        //
        //if($gift_log){
        //    //兑换车辆分支
        //    //向我的车库加入车
        //    DB::beginTransaction();
        //    $new_car = new MyCar();
        //    $new_car->uid = $this->user->id;
        //    $new_car->CarId = $car_id;
        //    $new_car->BuyTime = Carbon::now()->toDateTimeString();
        //    $new_car->BuyCredit = $car->getCredit();
        //
        //    $buyNewCar = $new_car->save();
        //
        //    $gift_log->is_used = 1;
        //    $updateGiftLog = $gift_log->save();
        //
        //    if($buyNewCar && $updateGiftLog){
        //        DB::commit();
        //        MessageRepo::push([
        //            'type'=>3,
        //            'user_id'=>$this->user->id,
        //            'to_user_id'=>$this->user->id,
        //            'text'=>sprintf('兑换了车辆:%s',$car->CarName),
        //            'record_id'=>0,
        //        ]);
        //        return $this->success('兑换成功');
        //    }
        //
        //    DB::rollback();
        //
        //    return $this->error(1,'兑换失败请重试');
        //
        //}else{
            //购买车辆分支
            //检查此车库存
            if($car->CarNum <=0){
                return $this->error(1,'此车库存不足');
            }
            //检查用户余额是否足够
            if($this->user->getCredit() < $car->getCredit()){
                return $this->error(1,'用户余额不足以购买此车');
            }
    
            //向我的车库加入车
            DB::beginTransaction();
            $new_car = new MyCar();
            $new_car->uid = $this->user->id;
            $new_car->CarId = $car_id;
            $new_car->BuyTime = Carbon::now()->toDateTimeString();
            $new_car->BuyCredit = $car->getCredit();
    
            $buyNewCar = $new_car->save();
            
            //扣除用户余额
            $decreUser = $memberRepo::decrementUserCredit($this->user,$car->getCredit());
    
            //减少此车库存
            $car->CarNum--;
            $carStock = $car->save();
    
            if($buyNewCar && $decreUser && $carStock){
                DB::commit();
                MessageRepo::push([
                    'type'=>3,
                    'user_id'=>$this->user->id,
                    'to_user_id'=>$this->user->id,
                    'text'=>sprintf(config('words.messages.buy_car'),$car->CarName),
                    'record_id'=>0,
                ]);
                return $this->success('购买成功');
            }
    
            DB::rollback();
    
            return $this->error(1,'购买失败请重试');
        //}
        
    }
    
    //买道具
    public function buyStage(MemberRepo $memberRepo)
    {
        $stage_id = $this->request->stage_id;
        $stage = Stage::findOrFail($stage_id);
        
        //检查用户余额是否足够
        if($this->user->getCredit() < $stage->getPrice()){
            return $this->error(1,'您的余额不足以购买此道具');
        }
        
        //添加道具
        DB::beginTransaction();
        $new_stage = new MyStage();
        $new_stage->uid = $this->user->id;
        $new_stage->StageID = $stage_id;
        $new_stage->BuyTime = Carbon::now()->toDateTimeString();
    
        $buyNewStage = $new_stage->save();
    
        //扣除用户余额
        $decreUser = $memberRepo::decrementUserCredit($this->user,$stage->getPrice());
        
        if($buyNewStage && $decreUser){
            DB::commit();
            return $this->success('购买成功');
        }
    
        DB::rollback();
        
        return $this->error(1,'购买失败请重试');
    }
    
    //金币小店
    public function scores()
    {
        return $this->success($this->goldShopService->goldShopList());
    }
    
    //抽奖 - 弃用
    public function buyScore()
    {
        return $this->success(['score'=>100]);
    }
}
